package com.huanletao.spring.util;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.MutablePropertySources;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/**
 * <p>
 *  PropertiesLoaderUtils 可以读取properties文件
 *  可以读取yml 配置文件, 将加载到properties对象中
 * </p>
 *
 * @package: com.huanletao.spring.util
 * @Description:
 * @className: PropertiesLoaderUtilsUniles
 * @author: @NNCSKJ ADMIN
 * @copyright: Copyright (c) 2022/7/29 17:18
 * @version: V1.0
 */
public class PropertiesLoaderUtilsUniles {

    /**
     *  ConfigurableEnvironment
     *  自己编码读取配置文件，装载到ConfigurableEnvironment 中，
     *  然后就可以跟spring @value进行配置使用读取配置信息；
     *
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();

        ConfigurableEnvironment environment =  applicationContext.getEnvironment();

        MutablePropertySources propertySources = environment.getPropertySources();

        DefaultResourceLoader resourceLoader = new DefaultResourceLoader();
        Resource resource = resourceLoader.getResource("configuration/config.properties");
        Properties properties = PropertiesLoaderUtils.loadProperties(resource);
        propertySources.addFirst(new PropertiesPropertySource("test",properties));

        applicationContext.registerBean("person",Person.class);

        applicationContext.refresh();
        Person bean = applicationContext.getBean(Person.class);
        System.out.println("bean = " + bean);
    }

}
